import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {HttpClient} from '@angular/common/http';
import {NzMessageService} from 'ng-zorro-antd';

@Component({
  selector: 'app-list',
  templateUrl: './list.component.html',
  styleUrls: ['./list.component.scss']
})
export class ListComponent implements OnInit {
  param = {
    pageNo: 1,
    pageSize: 10,
    count: 0
  };
  list = [];
  loadingFlag = true;
  isVisible = false;
  private deleteId;
  btnLoading = false;

  constructor(
    private router: Router,
    private http: HttpClient,
    private message: NzMessageService
  ) {
  }

  ngOnInit() {
    this.loadData();
  }

  loadData() {
    this.loadingFlag = true;
    this.http.post('/api/initialization/listServer', this.param).subscribe(res => {
      this.list = res[`data`];
      this.param.count = res[`count`];
      this.loadingFlag = false;
    });
  }

  add() {
    this.router.navigate(['/server/new']);
  }

  pageChange($event: number) {
    this.param.pageNo = $event;
    this.loadData();
  }

  delete(id: any) {
    this.deleteId = id;
    this.isVisible = true;
  }

  refresh(idx: any) {
    this.list[idx][`loading`] = true;
    const id = this.list[idx][`id`];
    this.http.post('/api/initialization/refreshServer/' + id, null).subscribe(() => {
      this.message.create('success', `服务器刷新成功`);
      this.loadData();
      this.list[idx][`loading`] = false;
    }, () => {
      this.message.create('error', `服务器连接失败`);
      this.list[idx][`loading`] = false;
    });
  }

  install(type: string, idx: any) {
    const id = this.list[idx][`id`];
    this.list[idx][`${type}Loading`] = true;
    this.http.post('/api/initialization/installSoft/' + id + '/' + type, null).subscribe(() => {
      this.message.create('warning', `${type}正在安装，请稍后刷新查看结果`);
      this.loadData();
      this.list[idx][`${type}Loading`] = false;
    });
  }

  okCallback() {
    this.btnLoading = true;
    this.http.delete('/api/initialization/deleteServer/' + this.deleteId).subscribe(() => {
      this.isVisible = false;
      this.btnLoading = false;
      this.loadData();
      this.message.success('删除成功', {
        nzDuration: 2000
      });
    });
  }

  copyMessage(val: any) {
    const selBox = document.createElement('textarea');
    selBox.style.position = 'fixed';
    selBox.style.left = '0';
    selBox.style.top = '0';
    selBox.style.opacity = '0';
    selBox.value = val;
    document.body.appendChild(selBox);
    selBox.focus();
    selBox.select();
    document.execCommand('copy');
    document.body.removeChild(selBox);
    this.message.create('success', `复制成功`);
  }
}
